package RestaurarImagen;

import java.awt.Color;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.List;
import java.util.*;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/* A median filter is a rank-order filter where the rank is 0.5 -- the 50th percentile.
 Median filters: This rank order filter is interesting because the median is the
most costly single rank that we could wish to obtain.
 */


public class Paso1_BSR {
   public BufferedImage aplica_paso1(BufferedImage imag){
        int width = imag.getWidth();
        int height = imag.getHeight();
        BufferedImage ejemplo = new BufferedImage(width,height, BufferedImage.TYPE_3BYTE_BGR);
        for(int i=1;i<width-1;i++){
            for(int j=1; j<height-1;j++){
                ejemplo.setRGB(i, j, mediana(i, j,imag));
            }
        }
        return ejemplo;
    }

    public int mediana(int i, int j, BufferedImage imag){
        int [] valores  = new int [9];
        int rojo, verde, azul;
        
        //Limites eliminados en el bucle que empieza en 1 y termina en tamaño-1
        //Valores de sus vecinos, mascara 3 x 3
        valores [0] =  (0x00ff0000 & imag.getRGB(i-1,j-1)) >> 16;
        valores [1] =  (0x00ff0000 & imag.getRGB(i,j-1)) >> 16;
        valores [2] =  (0x00ff0000 & imag.getRGB(i+1,j-1)) >> 16;
        valores [3] =  (0x00ff0000 & imag.getRGB(i-1,j)) >> 16;
        valores [4] =  (0x00ff0000 & imag.getRGB(i,j)) >> 16;
        valores [5] =  (0x00ff0000 & imag.getRGB(i+1,j)) >> 16;
        valores [6] =  (0x00ff0000 & imag.getRGB(i-1,j+1) >> 16);
        valores [7] =  (0x00ff0000 & imag.getRGB(i,j+1)) >> 16;
        valores [8] =  (0x00ff0000 & imag.getRGB(i+1,j+1)) >> 16;

        Arrays.sort(valores);
        rojo = valores[4];
        verde = (imag.getRGB(i,j) & 0x0000ff00) >> 8;
        azul = (imag.getRGB(i,j) & 0x000000ff);

        Color c = new Color (rojo, verde, azul);

       return c.getRGB();
    }
}
